<template>
    <div class="common-tabs-wrap">
        <Card :padding="0" dis-hover class="no-border-card">
            <p slot="title">
                公司指导用电配置 
                <Button type="ghost" size="small" class="btn-left" @click="changeState">{{str}}</Button>
                <Button type="ghost" size="small" @click="resetAll" v-if="strFlag == 2">取消</Button>
            </p>

            <Row type="flex" justify="space-between">
                <Col span="12" class="form-wrap">
                    <div class="cfg-sub-title">公司用电方案</div>
                    <Form ref="form1" :model="form1Data" :rules="form1Rules" :label-width="96" :show-message="false">

                        <FormItem label="公司电价" class="form-item" prop="ele_price">
                            <Row>
                                <Col style="width:220px" span="14">
                                    <InputNumber v-model="form1Data.ele_price" :min="0" :max="100" :formatter="formatInput" style="width: 100%;" :disabled="strFlag == 1"/>
                                </Col>
                                <Col span="6">&nbsp;&nbsp;元/度&nbsp;&nbsp;</Col>
                              
                            </Row>
                        </FormItem>

                        <FormItem label="付费模式" class="form-item" prop="pay_type">
                            <Row>
                                <Col style="width:220px" span="14">
                                    <Select v-model="form1Data.pay_type" :disabled="strFlag == 1">
                                        <Option v-for="item in ElemeterPayMode.properties" :value="item.type" :key="item.type">{{ item.text }}</Option>
                                    </Select>
                                </Col>
                            </Row>
                        </FormItem>

                        <FormItem label="透支额度" class="form-item" v-show="form1Data.pay_type == ElemeterPayMode.PREPAID">
                            <Row>
                                <Col style="width:220px" span="8">
                                    <InputNumber v-model="form1Data.overdraft_amount" :min="0"  :max="999" 
                                    style="width: 100%;" :disabled="strFlag == 1"/>

                                    <!-- <Input v-model="form1Data.overdraft_amount" placeholder="精确到小数点后四位" :maxlength="10" clearable></Input> -->
                                </Col>
                                <Col span="6">&nbsp;&nbsp;度</Col>
                            </Row>
                        </FormItem>

                        <FormItem label="断电提醒" class="form-item" v-show="form1Data.pay_type == ElemeterPayMode.PREPAID">
                            <Row>

                                <Col style="width:220px" span="14">
                                    <Select v-model="form1Data.low_warn" :disabled="strFlag == 1">
                                        <Option v-for="item in LowWarnValues" :value="item" :key="item">{{ item }}</Option>
                                    </Select>
                                </Col>
                                <Col span="8">&nbsp;&nbsp;度</Col>
                            </Row>
                        </FormItem>
                    </Form>
                </Col>

                <Col span="12" class="form-wrap form-wrap2">
                    <div class="cfg-sub-title" style="margin-left:14px;">公司公摊预设</div>
                    <Form ref="form2" :label-width="140" :show-message="false" class="form2">
                        <FormItem label="是否开启公摊预设">
                            <span>{{use_pool?'已开启':'已关闭'}}</span>
                            <i-switch :disabled="strFlag == 1" v-model="use_pool"></i-switch>
                        </FormItem>

                        <FormItem label="公区电表计量方式">
                            <Select :disabled="strFlag == 1" v-model="pool_area_type" style="width: 220px;">
                                <Option v-for="item in pool_area_types" :value="item.id" :key="item.id">{{ item.text }}</Option>
                            </Select>
                            <Button type="ghost" v-show="isForm2Change" @click="saveChargeParty('form2')">保存</Button>
                        </FormItem>

                        <div style="padding-left:14px">
                        注：仅新建房源时初始化配置该项，如需变更请通过房源用电配置操作
                        </div>
                        
                    </Form>
                </Col>
            </Row>

        </Card>

        <Card dis-hover class="no-border-card" style="margin-top:15px">
                <p slot="title">
                    门店自定义配置列表
                    <Button type="primary" 
                    class="btn-in-top-large"
                    @click="exportList">
                    导出列表
                    </Button>	
                </p>

                <Table :columns="columns" :data="tableData" :loading="loadingTable"/>

        </Card>
        <Page v-if="total" :current.sync="currPage" :total="total" :page-size="limit" show-elevator show-total style="text-align:center" @on-change="onPageChange"></Page>

    </div>
</template>

<script>
import { ElemeterPayMode, LowWarnValues } from '@/libs/const'
import { http, api } from '@/libs/http'
import util from '@/libs/util'
// import validate from '@/libs/validate';

const LIMIT = 15
const ListTypes = [{ id: 1, text: '按门店查看' }, { id: 2, text: '按房源查看' }, { id: 3, text: '按房间查看' }]

let _params = {
  type: 1,
  offset: 0,
  limit: LIMIT
}

export default {
  name: 'companyCfg',
  props: {
    tableHeaders: Function
  },
  data () {
    return {
      strFlag: 1,
      loadingTable: false,
      ElemeterPayMode: ElemeterPayMode,

      use_pool: false,
      pool_area_type: 1,
      pool_area_types: [
        // { id: 0, text: ''}, //云丁承担
        { id: 1, text: '公区总电表模式' },
        { id: 2, text: '公区独立电表模式' }
      ],

      form1Data: {
        ele_price: 0,
        pay_type: null,
        overdraft_amount: 0,
        low_warn: 0
      },
      saveOldData: {}, // 保存初始房间配置
      form1Rules: {
        pay_type: [{ required: true, type: 'integer', message: '', trigger: 'blur' }]
      },

      form2Data: {
        poundage_type: 1
      },

      listTypes: ListTypes,
      listType: 1,

      currPage: 1,
      total: 0,
      limit: LIMIT,
      columns: [],
      cfgList: [],
      tableData: [],

      orign1Data: null,
      orign2Data: null,

      LowWarnValues
    }
  },

  computed: {
    str () {
      return this.strFlag === 1 ? '编辑' : '保存'
    },
    isForm1Change () {
      if (this.orign1Data && this.hasChanged(this.orign1Data, this.form1Data)) {
        return true
      }
      return false
    },
    isForm2Change () {
      if (this.orign2Data && this.hasChanged(this.orign2Data, this.form2Data)) {
        return true
      }
      return false
    },
    payType () {
      return this.form1Data.pay_type
    }
  },

  mounted () {
    this.columns = this.tableHeaders(1)
    this.getEleSettingInfo()
    this.loadSettingList()
  },

  watch: {
    payType (newVal, oldVal) {
      // 付费模式切换,防止数据初始化时数据变化出现弹窗
      if (typeof oldVal !== 'object') {
        this.$Modal.warning({
          title: newVal === 2 ? '预付费切换后付费' : '后付费切换预付费',
          content: '公司付费模式修改，只影响即将绑定的房间。已绑定电表的房间付费模式不同步更新。',
          // content:
          //     newVal == 2
          //         ? `<p>切换后，所有使用公司统一方案的门店、房源及房间均会同步切换。剩余电量及充值电量将清零。为避免影响使用，建议记录相关房间数据后切换</p>`
          //         : `<p>切换后，所有使用公司统一方案的门店、房源及房间均会同步切换。如房间剩余电量不足将自动断电。为避免影响使用，建议切换后，及时通知租客充值<p>`,
          okText: '我已知悉'
        })
      }
    }
  },

  methods: {
    getEleSettingInfo () {
      http.request(this, api.clients_elemeter_setting_info, null, null, (res, err) => {
        if (err || !res) {
          return
        }
        let { ele_price, pay_type, overdraft_amount, low_warn, use_pool, pool_area_type } = res
        this.use_pool = use_pool || false
        this.pool_area_type = pool_area_type || 1
        this.form1Data = {
          ele_price: Number(ele_price || 0),
          pay_type,
          overdraft_amount: Number(overdraft_amount || 0),
          low_warn: Number(low_warn || 0)
        }

        this.saveOldData = Object.assign({}, this.form1Data) // 浅拷贝

        this.form2Data.poundage_type = res.poundage_type

        this.orign1Data = util.deepNormalCopy(this.form1Data)
        this.orign2Data = util.deepNormalCopy(this.form2Data)
      })
    },
    formatInput (newVal) {
      if (newVal < 0) {
        return 1
      } else {
        return newVal
      }
    },
    resetAll () {
      this.form1Data = Object.assign({}, this.saveOldData)
      this.strFlag = 1
    },
    changeState () {
      // 修改按钮状态并且看按钮状态考虑是否保存
      if (this.strFlag === 1) this.strFlag = 2
      else this.saveCompanyCfg('form1')
    },
    renderStr (key, row, type) {
      const datas = this.orign1Data || {}
      let style = {}
      let standardVal
      let storeVal
      let text
      if (type === 1) {
        standardVal = datas[key] || ''
        storeVal = row[key]
        text = storeVal ? (storeVal === 1 ? '预付费' : '后付费') : '-'
      } else {
        standardVal = Number(datas[key]) || ''
        storeVal = Number(row[key])
        text = row[key] ? storeVal.toFixed(4) : '-'
      }
      if (text !== '-' && standardVal !== storeVal) {
        style.color = 'red'
        style.fontWeight = '600'
      }
      return ['span', { style }, text]
    },
    loadSettingList () {
      this.loadingTable = true
      http.request(this, api.clients_elemeter_setting_list, null, _params, (res, err) => {
        this.loadingTable = false
        if (err || !res) {
          return
        }

        this.total = res.count
        this.tableData = res.rows.map(item => {
          const { elemeter_setting: setting } = item
          return {
            ...item,
            ele_price: (setting && setting.ele_price) || '',
            low_warn: (setting && setting.low_warn) || '',
            overdraft_amount: (setting && setting.overdraft_amount) || '',
            pay_type: (setting && setting.pay_type) || ''
          }
        })
      })
    },
    hasChanged (obj1, obj2) {
      for (let i in obj1) {
        if (obj1[i] !== obj2[i]) {
          return true
        }
      }
      return false
    },
    saveCompanyCfg (name) {
      let form1Data = this.form1Data

      if (!form1Data.ele_price) {
        this.$Message.info('公司电价设置错误')
        return
      }

      if (!form1Data.pay_type) {
        this.$Message.info('付费模式设置错误')
        return
      }

      if (form1Data.pay_type === 1 && (!form1Data.overdraft_amount || form1Data.overdraft_amount < 0.01)) {
        this.$Message.info('公司透支额度最少为0.01')
        return
      }

      if (form1Data.pay_type === 1 && !form1Data.low_warn) {
        this.$Message.info('公司断电提醒设置错误')
        return
      }

      let params = {
        pay_type: form1Data.pay_type,
        ele_price: Number(form1Data.ele_price.toFixed(4)),
        use_pool: this.use_pool,
        pool_area_type: this.pool_area_type
      }

      if (form1Data.pay_type === ElemeterPayMode.PREPAID) {
        params.ele_price = Number(form1Data.ele_price.toFixed(4))
        params.overdraft_amount = Number(form1Data.overdraft_amount.toFixed(2))
        params.low_warn = form1Data.low_warn
      }

      this.$refs[name].validate(valid => {
        if (!valid) {
          return
        }
        if (params.ele_price > 5) {
          this.$Message.info('电价设置最大不能超过5元')
          return
        }

        http.request(this, api.clients_elemeter_setting_update, null, params, (res, err) => {
          if (err || !res) {
            return
          }
          this.selectListType(this.listType)
          this.$Message.success('保存成功')
          this.orign1Data = util.deepNormalCopy(this.form1Data)
          this.strFlag = 1
          this.getEleSettingInfo()
        })
      })
    },

    saveChargeParty (name) {
      let form2Data = this.form2Data
      let params = {
        poundage_type: form2Data.poundage_type
      }

      http.request(this, api.clients_poundage_type_update, null, params, (res, err) => {
        if (err || !res) {
          return
        }
        this.$Message.success('保存成功')
        this.orign2Data = util.deepNormalCopy(this.form2Data)
      })
    },

    selectListType (type) {
      _params.offset = 0
      _params.type = type
      this.currPage = 1
      this.columns = this.tableHeaders(type)
      this.loadSettingList()
    },

    exportList () {
      // 导出报表
      http.exportTable(this, api.company_config_export, null, null)
    },

    onPageChange (page) {
      _params.offset = (page - 1) * LIMIT
      this.loadSettingList()
    }
  }
}
</script>

<style lang="less" scoped>
.form-wrap {
    padding: 20px 10px 20px 10px;
    margin-left: -10px;
}
.form-wrap2 {
    padding-left: 40px;
    border-left: 1px dashed #bbbec4;
}
.form2 {
    height: 100%;
}
.form-item {
    margin-bottom: 15px;
    text-align: left;
}

.list-tab {
    margin: 10px 0 0;
}
.space {
    width: 10px;
}
.table {
    margin: 10px 0;
}
.btn-left {
    margin-left: 10px;
}
.cfg-sub-title {
    margin-left: 22px;
    margin-bottom: 15px;
    font-weight: bold;
    font-size: 14px;
}
.ivu-card-body {
    border: 1px solid #e9eaec;
}

</style>
